package com.shouer.doc.ui.login.presenter;


import android.net.Uri;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.shouer.doc.BuildConfig;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.common.util.FileUtil;
import com.shouer.doc.common.util.SPUtils;
import com.shouer.doc.common.util.Tools;
import com.shouer.doc.event.LoginToRongEvent;
import com.shouer.doc.request.GsonRequest;
import com.shouer.doc.request.RequestUtil;
import com.shouer.doc.ui.login.model.DoctorInfoModel;
import com.shouer.doc.ui.login.model.UserModel;
import com.shouer.doc.ui.login.response.GetTokenResponse;
import com.shouer.doc.ui.login.response.LoginResponse;
import com.shouer.doc.ui.login.response.WeChatLoginResponse;
import com.shouer.doc.ui.login.view.ILoginView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

/**
 * Created by ZXL on 2016/11/12.
 */

public class LoginPresenterCompl implements ILoginPresenter {

    private ILoginView mLoginView;
    private boolean isFirstLoginToRong=true;
    private UserModel userModel;
    private DoctorInfoModel doctorInfoModel;

    public LoginPresenterCompl(ILoginView loginView) {
        this.mLoginView = loginView;
        EventBus.getDefault().register(this);
    }


    @Override
    public void doLogin(String name, String password) {

        Map<String, String> param = new HashMap<>();
        param.put("userPhone", name);
        param.put("password", password);
        param.put("os", "0");
        param.put("uuid",  Tools.getUUID(mLoginView.getActivity()));

        final GsonRequest<LoginResponse> request = new GsonRequest(ShouerConst.APP_SERVER_https,"docLogin", LoginResponse.class, new Response.Listener<LoginResponse>() {
            @Override
            public void onResponse(LoginResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mLoginView.loginFailed("登录失败 网络异常1");
            }
        });

        RequestUtil.sendRequest(mLoginView.getActivity(), param, request);
    }

    /**
     * 微信登录
     * */
    @Override
    public void wechatLogin(String code, String token, String refreshToken) {

        Map<String, String> param = new HashMap<>();
        param.put("code", code);
        param.put("refreshToken", refreshToken);
        param.put("token", token);

        final GsonRequest<WeChatLoginResponse> request = new GsonRequest(ShouerConst.APP_SERVER_https,"docWeChatLogin", WeChatLoginResponse.class, new Response.Listener<WeChatLoginResponse>() {
            @Override
            public void onResponse(WeChatLoginResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mLoginView.wechatLoginFailed("登录失败 网络异常1");
            }
        });

        RequestUtil.sendRequest(mLoginView.getActivity(), param, request);

    }

    @Override
    public void loginToRongCloud(String rongToken) {
        Log.d(LoginPresenterCompl.class.getSimpleName(),"loginToRongCloud------:"+rongToken);
        RongIM.connect(rongToken, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Log.e(LoginPresenterCompl.class.getSimpleName(),"onTokenIncorrect()");
                EventBus.getDefault().post(new LoginToRongEvent(false));
            }

            @Override
            public void onSuccess(String s ) {
                Log.d(LoginPresenterCompl.class.getSimpleName(),"onSuccess:"+s);
                EventBus.getDefault().post(new LoginToRongEvent(true));
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

                Log.d(LoginPresenterCompl.class.getSimpleName(), "--onError" + errorCode);
                if (errorCode != RongIMClient.ErrorCode.RC_CONN_OVERFREQUENCY) {
                    EventBus.getDefault().post(new LoginToRongEvent(false));
                } else {
                    EventBus.getDefault().post(new LoginToRongEvent(true));
                }
            }
        });

    }

    @Override
    public void getTokenFromServer(String userId) {

        Map<String, String> param = new HashMap<>();
        param.put("userId",  userId);

        final GsonRequest<GetTokenResponse> request = new GsonRequest("getToken", GetTokenResponse.class, new Response.Listener<GetTokenResponse>() {
            @Override
            public void onResponse(GetTokenResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mLoginView.loginFailed("登录失败 网络异常2");
            }
        });

        RequestUtil.sendRequest(mLoginView.getActivity(), param, request);

    }

    /**
     * 客户端登录接口返回
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginResponse loginResponse)
    {
        if (loginResponse.getErrorCode()>=0)
        {
            loginResponse.getUser().setRongToken(loginResponse.getToken());
            userModel = loginResponse.getUser();
            doctorInfoModel=loginResponse.getDoctor();
            loginToRongCloud(userModel.getRongToken());

        }else
        {
            mLoginView.loginFailed(loginResponse.getErrorMsg());
        }
    }

    /**
     * 微信登录接口回调函数
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(WeChatLoginResponse response)
    {
        if (response.getErrorCode()>=0)
        {
            response.getUser().setRongToken(response.getToken());
            userModel = response.getUser();
            doctorInfoModel=response.getDoctor();
            mLoginView.wechatLoginSuccess(response);
            loginToRongCloud(userModel.getRongToken());

        }else
        {
            SPUtils.remove(mLoginView.getActivity(),"wx_token");
            SPUtils.remove(mLoginView.getActivity(),"wx_refresh_token");
            if (response.getErrorCode()==-100)
            {
                mLoginView.bindWeChat(response.getRefreshToken(),response.getWxToken());
            }else
            {
                mLoginView.wechatLoginFailed(response.getErrorMsg());
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(GetTokenResponse response)
    {
        if (response.getErrorCode()>=0)
        {
            userModel.setRongToken(response.getToken());
            loginToRongCloud(response.getToken());
        }else
        {
            mLoginView.loginFailed(response.getErrorMsg());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginToRongEvent event) {
        if (BuildConfig.LOG_DEBUG) {
            Log.e(ILoginPresenter.class.getSimpleName(), "LoginToRongEvent");
        }
        if (event.isSuccess()) {
            RongIM.getInstance().setCurrentUserInfo(new UserInfo(doctorInfoModel.getDocId(),
                    doctorInfoModel.getDocName(),
                    Uri.parse(FileUtil.connectFilePath(ShouerConst.RES_SERVER, doctorInfoModel.getDocImageUrl()))));
            RongIM.getInstance().setMessageAttachedUserInfo(true);
            mLoginView.getApp().setUserModel(userModel);
            mLoginView.getApp().setUserDocInfo(doctorInfoModel);
            mLoginView.loginSuccess();
        } else {
            if (!isFirstLoginToRong) {
                mLoginView.loginFailed("登录失败!");
            } else {
                isFirstLoginToRong = false;
                getTokenFromServer(userModel.getUserId());
            }
        }
    }



    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
    }
}
